package com.example.bean;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.example.entity.Perminssion;
import com.example.entity.Role;
import com.example.entity.User;

/*
 * 权限控制用户实体类
 */
public class UserDetailImpl implements UserDetails, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String username;
    private String password;
    private Set<? extends GrantedAuthority> authorities;
    
    public UserDetailImpl() {
    }
    
    //构造函数，用User类构造UserDetails类
    public UserDetailImpl(User user) {
    	this.username = user.getUsername();
    	this.password = user.getPassword();
        
        Set<GrantedAuthority> authoritiesSet = new HashSet<GrantedAuthority>();
        
        List<Role> roles = user.getRoles();
        
        for(Role role: roles) {
        	List<Perminssion> rights = role.getPerminssions();
        	for(Perminssion right: rights)
        		authoritiesSet.add(new SimpleGrantedAuthority(right.getUrl()));
        }
        
        this.authorities = authoritiesSet;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    public void setAuthorities(Set<? extends GrantedAuthority> authorities) {
        this.authorities = authorities;
    }

    @Override
    public String getPassword() { // 最重点Ⅰ
        return this.password;
    }

    @Override
    public String getUsername() { // 最重点Ⅱ
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
